package com.qinggeng.project.api.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.redis.RedisLock;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.DistributionPointDto;
import com.qinggeng.project.api.dto.ShopDto;
import com.qinggeng.project.api.dto.ShopStatisDto;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.factory.DistributionPointImgFactory;
import com.qinggeng.project.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.qinggeng.project.api.security.utils.ApiUtils.getIsLogin;

@Api(tags = "首页模块")
@RestController
@RequestMapping("${apiPath}/index")
@CrossOrigin("*")
public class ApiIndexController extends BaseController {

    @Autowired
    private IShopService shopService;

    @Autowired
    private IGoodsSigninService goodsSigninService;

    @Autowired
    private IUserGiftService userGiftService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ISysNewsService sysNewsService;

    @Autowired
    private IUserMessageService userMessageService;

    @Autowired
    private IGoodsActiviyService goodsActiviyService;

    @Autowired
    private IUserAddressService userAddressService;

    @Autowired
    private IDistributionPointService distributionPointService;

    @Autowired
    private IOrdersPointService ordersPointService;

    @Autowired
    private DistributionPointImgFactory pointImgFactory;



    @Autowired
    private RedisCache redisCache;

    @ApiOperation("收货地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name="lng",value="经度",dataType="Float", paramType = "query",required = true),
            @ApiImplicitParam(name="lat",value="纬度",dataType="Float", paramType = "query",required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = false)

    })
    @GetMapping("/address")
    @LoginRequired(must = false)
    public AjaxResult userAddress(Float lng,Float lat){
        //根据用户当前定位获取用户添加的距离最近的收货地址
        UserAddress address=null;
        if(getIsLogin()){
            address=userAddressService.selectUserAddressByLocation(ApiUtils.getUserId(),lng,lat);
        }
        Map<String,Object> data=Maps.newHashMap();
        data.put("address",address);
        return AjaxResult.success(data);
    }
    @ApiOperation("门店选择")
    @ApiImplicitParams({
            @ApiImplicitParam(name="shopId",value="商铺Id",dataType="Long", paramType = "query",required = true),
            @ApiImplicitParam(name="pointId",value="配送点Id",dataType="Long", paramType = "query"),
            @ApiImplicitParam(name="addressId",value="收货地址Id",dataType="Long", paramType = "query"),
            @ApiImplicitParam(name="lng",value="经度",dataType="Float", paramType = "query",required = true),
            @ApiImplicitParam(name="lat",value="纬度",dataType="Float", paramType = "query",required = true),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记")
    })
    @GetMapping("/point")
    @LoginRequired(must = false,role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult point(Long shopId,Long pointId,Long addressId,Float lng, Float lat){
        DistributionPointDto pointDto = distributionPointService.systemSelectPoint(shopId, pointId, addressId, lng, lat);
        if (pointDto == null){
            logger.error("pointDto is null");
            throw new CustomException("自提点查询为空");
        }
        return AjaxResult.success(pointDto);
    }

    @ApiOperation("附近商家")
    @GetMapping("/shopList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", value = "搜索", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "经度", dataType = "Float", paramType = "query"),
            @ApiImplicitParam(name = "lat", value = "纬度", dataType = "Float", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
    })
    public AjaxResult shopList(Float lng, Float lat, String search) {
        startPage();
        Shop where = new Shop();
        where.setLng(lng);
        where.setLat(lat);
        where.setName(search);
        List<ShopDto> shopList = shopService.selectShopDtoList(where);
        for (ShopDto shop : shopList) {
            shop.setShopLog(shop.getShopLog().split(",")[0]);
        }
        return AjaxResult.success(shopList);
    }


    @ApiOperation("礼品列表")
    @GetMapping("/goodsSigninList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "indexType", value = "0=新人福利，1=签到礼品", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = false)
    })
    @LoginRequired(must = false, role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult goodsSigninList(Integer indexType) {
        GoodsSignin where = new GoodsSignin();
        where.setIndexType(indexType);
        List<GoodsSignin> goodsSigninList = goodsSigninService.selectGoodsSigninList(where);
        if (indexType == 0) {
            if (getIsLogin()) {
                //判断今日是否领取签到
                UserGift giftWhere = new UserGift();
                giftWhere.setGiftType(CommonEnum.STATUS_20.getValue());
                giftWhere.setUserId(ApiUtils.getUserId());
                if (userGiftService.selectUserGiftList(giftWhere).size() > 0) {
                    return AjaxResult.error(-100, "已领取新人礼包无法重复领取", ShowTypeEnum.用户.getValue());
                }
            }
        } else {
            String[] weekArray = new String[7];
            Date weekOne = DateUtils.getThisWeekMonday(DateUtils.getNowDate());
            Calendar cal = Calendar.getInstance();
            cal.setTime(weekOne);
            weekArray[0] = DateUtils.parseDateToStr("yyyy-MM-dd", cal.getTime());
            for (int i = 1; i < 7; i++) {
                cal.add(Calendar.DAY_OF_MONTH, 1);
                weekArray[i] = DateUtils.parseDateToStr("yyyy-MM-dd", cal.getTime());
            }
            if (getIsLogin()) {
                for (int i = 0; i < goodsSigninList.size(); i++) {
                    if (userGiftService.selectUserGiftByUserId(CommonEnum.STATUS_10.getValue(), weekArray[i], ApiUtils.getUserId()) != null) {
                        goodsSigninList.get(i).setIsGet(true);
                    }
                }
            }
        }
        return AjaxResult.success(goodsSigninList);
    }


    @ApiOperation("签到领取")
    @GetMapping("/addSignin")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "signinId", value = "签到ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult addSignin(Long signinId) {
        RedisLock redisLock = new RedisLock(redisTemplate, "addSignin:" + ApiUtils.getUserId(), 3 * 1000, 3 * 1000);
        if (!redisLock.lockNoRetry()) {
            return AjaxResult.error("服务繁忙，请休息一会",ShowTypeEnum.用户.getValue());
        }
        GoodsSignin goodsSignin = goodsSigninService.selectGoodsSigninById(signinId);
        if (goodsSignin == null) {
            return AjaxResult.error("礼品不存在");
        }
        //判断今日是否领取签到
        if (userGiftService.selectUserGiftByUserId(CommonEnum.STATUS_10.getValue(), DateUtils.parseDateToStr("yyyy-MM-dd", DateUtils.getNowDate()), ApiUtils.getUserId()) != null) {
            return AjaxResult.error("已签到无法重复签到",ShowTypeEnum.用户.getValue());
        }
        return toAjax(userGiftService.addSignin(signinId, ApiUtils.getUserId()));
    }

    @ApiOperation("新人礼包领取")
    @GetMapping("/addGift")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult addGift() {
        //判断今日是否领取签到
        UserGift where = new UserGift();
        where.setGiftType(CommonEnum.STATUS_20.getValue());
        where.setUserId(ApiUtils.getUserId());
        if (userGiftService.selectUserGiftList(where).size() > 0) {
            return AjaxResult.error("已领取新人礼包无法重复领取");
        }
        return toAjax(userGiftService.addGift(ApiUtils.getUserId()));
    }

    /**
     * 根据店铺ID查询店铺信息
     */
    @ApiOperation("根据店铺ID查询店铺信息")
    @GetMapping("/getShopInfoById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "店铺ID", dataType = "Long", paramType = "query"),
    })
    public AjaxResult getShopInfoById(Long id) {
        ShopStatisDto shopStatisDto = shopService.getShopInfoById(id);
        return AjaxResult.success(shopStatisDto);
    }

    /**
     * 首页消息
     */
    @ApiOperation("首页消息")
    @GetMapping("/indexNews")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult indexNews() {
        try {
            //查询所有消息列
            List<News> newsList = sysNewsService.selectNewsAll();
            if (newsList == null || newsList.size() == 0) {
                throw new CustomException("系统异常");
            }
            ArrayList<Object> list = Lists.newArrayList();
            for (News news : newsList) {
                //物流消息
                if (news.getNewsCategory().equals("10")){
                    //查询用户最新消息
                    UserMessage userMessages = userMessageService.selectFirstUserMessageList(ApiUtils.getUserId());
                    if (userMessages == null) {
                        userMessages = new UserMessage();
                    }
                    HashMap<String , Object> resultMap = Maps.newHashMap();
                    resultMap.put("newsCategory",news.getNewsCategory());
                    resultMap.put("title",news.getNewsName());
                    resultMap.put("picture",news.getPicture());
                    resultMap.put("isOfficial",news.getIsOfficial());
                    resultMap.put("content", userMessages.getFkMark());
                    list.add(resultMap);
                }
                //活动消息
//                    if (news.getNewsCategory().equals("20")){
//                    //查询最新商品活动
//                    GoodsActivity goodsActivity = goodsActiviyService.selectFirstGoodsActivity();
//                    if (goodsActivity == null) {
//                        goodsActivity = new GoodsActivity();
//                    }
//                        HashMap<String , Object> resultMap = Maps.newHashMap();
//                        resultMap.put("newsCategory",news.getNewsCategory());
//                        resultMap.put("title",news.getNewsName());
//                        resultMap.put("picture",news.getPicture());
//                        resultMap.put("isOfficial",news.getIsOfficial());
//                        resultMap.put("content", goodsActivity.getActivityName());
//                        list.add(resultMap);
//                }

            }
            return AjaxResult.success(list);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }




    /**
     * 口令加密
     */
    @ApiOperation("口令生成加密")
    @GetMapping("/pwdGenEncryption")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "str", value = "加密字符串", dataType = "String", paramType = "query"),
    })
    public AjaxResult passwordGenerationEncryption(String str) {
        byte[] bytes = str.getBytes();
        String encoded = Base64.getEncoder().encodeToString(bytes);
        return AjaxResult.success(encoded);
    }

    /**
     * 口令解密
     */
    @ApiOperation("口令解密")
    @GetMapping("/pwdGenDecryption")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "str", value = "解密字符串", dataType = "String", paramType = "query"),
    })
    public AjaxResult passwordGenerationDecryption(String str) {
        byte[] decoded = Base64.getDecoder().decode(str);
        String decodeStr = new String(decoded);
        return AjaxResult.success(decodeStr);
    }
}
